//
//  M4HistoryViewController.swift
//  M4
//
//  Created by YuChuang on 2024/8/9.
//

import UIKit

class M4HistoryViewController: M4BaseViewController {
    
    @IBOutlet weak var M4HisRepayButton: UIButton!
    
    @IBOutlet weak var M4HisRepayLine: UIView!
    
    @IBOutlet weak var M4HisOtherButton: UIButton!
    
    @IBOutlet weak var M4HisOtherLine: UIView!
    
    private var M4ListModel: M4LoanResultModel?
    
    lazy var M4NullView: M4DataNullView = {
        let nullV = UINib(nibName: "M4DataNullView", bundle: nil).instantiate(withOwner: self).last as! M4DataNullView
        nullV.M4NullUpdateUI(describe: "No hay préstamos pendientes de pago", buttonTitle: "Pedir un préstamo")
        nullV.M4NullButtonBlock = {
            self.navigationController?.popViewController(animated: false)
            M4BaseViewController.M4CurrentVC()?.tabBarController?.selectedIndex = 0
        }
        return nullV
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        M4NavBarColor = .white
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        M4BackIcon = "icon_back_black"
        M4NavTitle(M4Title: "Historial de préstamos", M4NavTitleColor: COLOR_333333)
        M4HisRepayButton.isSelected = true
        M4HisRepayButton.titleLabel?.font = M4HisRepayButton.isSelected ? UIFont.systemFont(ofSize: 14, weight: .bold) : UIFont.systemFont(ofSize: 14, weight: .regular)
        M4HisRepayLine.isHidden = false
        M4HisOtherButton.titleLabel?.font = M4HisOtherButton.isSelected ? UIFont.systemFont(ofSize: 14, weight: .bold) : UIFont.systemFont(ofSize: 14, weight: .regular)
        M4HisOtherLine.isHidden = true
        view.addSubview(M4TableView)
        M4TableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(M4HisRepayButton.snp.bottom)
            make.bottom.equalToSuperview().offset(-M4SafeDistanceBottom())
        }
        M4addRefreshToTaleView { [weak self] in
            let status = self?.M4HisRepayButton.isSelected == true ? 2 : 3
            self?.M4HistoryListNet(orderStaus: status)
        }
        M4HistoryListNet(orderStaus: 2)
    }
    
    @IBAction func M4HisRepayAction(_ sender: UIButton) {
        sender.isSelected = true
        sender.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .bold)
        M4HisRepayLine.isHidden = false
        M4HisOtherButton.isSelected = false
        M4HisOtherButton.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        M4HisOtherLine.isHidden = true
        M4HistoryListNet(orderStaus: 2)
    }
    
    
    @IBAction func M4HisOtherAction(_ sender: UIButton) {
        sender.isSelected = true
        sender.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .bold)
        M4HisOtherLine.isHidden = false
        M4HisRepayButton.isSelected = false
        M4HisRepayButton.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        M4HisRepayLine.isHidden = true
        M4HistoryListNet(orderStaus: 3)
    }
    
    override func M4CellAction(_ action: M4IDAction) {
        let type = M4HistoryRepayAction(rawValue: action.M4ActionType)
        if type == .M4HisPagaAction {
            let data = action.M4ActionData as? Int
            let page = M4PagoDetailViewController()
            page.M4PagoId = data ?? 0
            self.navigationController?.pushViewController(page, animated: true)
        }
        else if type == .M4ProrrogaAction {
            let data = action.M4ActionData as? M4LoanOrderListModel
            let page = M4ProrrogaDetiailViewController()
            page.M4ProrrogaData = data?.XPvy?[0]
            page.M4MainLoanId = data?.Jajlc ?? 0
            page.M4ProductItemCode = data?.NbN ?? ""
            page.productName = data?.LcMnJMQqO ?? ""
            self.navigationController?.pushViewController(page, animated: true)
        }
        else if type == .M4HisCellAction {
            let loanData = action.M4ActionData as? M4LoanOrderListModel
            M4UserDataManager.m4UserShare.M4ProductCode = loanData?.NbN ?? ""
            let page = M4LoanResultViewController()
            page.M4LoanId = loanData?.Jajlc ?? 0
            self.navigationController?.pushViewController(page, animated: true)
        }
    }
    
    override func M4DataRefresh() {
        let status = M4HisRepayButton.isSelected ? 2 : 3
        M4HistoryListNet(orderStaus: status)
    }

}

extension M4HistoryViewController {
    
    private func M4HistoryDataSource() {
        M4TableSources.removeAll()
        M4ListModel?.QKDLhYTHobF?.forEach({ order in
            if M4HisRepayButton.isSelected {
                M4TableSources.append(M4TableViewCellData("M4HisRepayCell", XIB: true, order))
            }
            else {
                M4TableSources.append(M4TableViewCellData("M4HistoryOtherCell", XIB: true, order))
            }
        })
        M4TableView.reloadData()
        M4TableView.backgroundView = M4ListModel?.QKDLhYTHobF?.count ?? 0 <= 0 ? M4NullView : nil
    }
    
    
    private func M4HistoryListNet(orderStaus: Int) {
        let para: [String : Any] = ["YjWGJmF": "ESP", "DnVc": M4UserDataManager.m4UserShare.M4Itemcode, "IxENPg": M4UserDataManager.m4UserShare.M4Token, "Uvmyi": orderStaus]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4OrderDetail, .post, params: para)) { model in
            self.M4endRefresh()
            self.M4HisRepayButton.M4EventUnavailable = false
            self.M4HisOtherButton.M4EventUnavailable = false
            if model.code == 1 {
                let data = model.data as? [String : Any]
                let models = data?.kj.model(M4LoanResultModel.self)
                if orderStaus == 3 {
                    //过滤已经关闭的订单
                    self.M4ListModel?.QKDLhYTHobF = models?.QKDLhYTHobF?.filter({ m in
                        return m.VRFYc != 7 && m.VRFYc != 6
                    })
                } else {
                    self.M4ListModel = models
                }
            }
            else {
                self.view.makeToast(model.message, position: .center)
            }
            self.M4HistoryDataSource()
        }
    }
    
}
